// pages/user/user-message-add/index.js
const app = getApp()
import {
  request,
  deepClone
} from '../../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    error: '',
    formData: {},
    rules: [{
      // name: 'name',
      // rules: {
      //   required: true,
      //   message: '姓名是必填项'
      // },
      name:'IDcard',
      rules: {
        rangelength: [18,18],
        message: '请输入正确的身份证号码~'
      }
    }],
    // 输入框的显示 (false) 和隐藏 (true)
    hideStatus: {
      IDcard: true, //身份证
      graduationSchool: true, //毕业院校
      graduationProfession: true, // 毕业专业
      graduationID: true, // 毕业证书编号
    },
    nationArr: ["汉族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "朝鲜族", "满族", "侗族", "瑶族", "白族",
      "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "傈僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族",
      "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族",
      "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族", "赫哲族", "门巴族", "珞巴族", "基诺族"
    ],
    education_bgArr: ["初中及以下", "高中", "中专", "大专", "本科"],
    gender: null, // 性别
    nation: '', // 民族
    hk_address: [], // 户口所在地（市区）的值
    hk_addressText: '', // 户口所在地（市区）显示的文字
    name: '', // 姓名
    phone: '', // 手机
    IDcard: '', // 身份证号码
    education_bg: 'null', // 前置学历层次
    graduationSchool: '', // 毕业院校
    graduationProfession: '', // 毕业专业
    graduationTime: '', // 毕业时间
    graduationID: '', // 毕业证书编号
    exam_address: [], // 首选考试县区（市区）的值
    exam_addressText: '', // 首选考试县区（市区）显示的文字
    standby_exam_address: [], // 备选考试县区（市区）的值
    standby_exam_addressText: '', // 备选考试县区（市区）显示的文字
    school: '', // 报读院校
    profession: '', // 报读专业
    level: '', // 报读层次
    take_info: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let {
      gender,
      nation,
      hk_address,
      name,
      phone,
      IDcard,
      education_bg,
      graduationSchool,
      graduationProfession,
      graduationTime,
      graduationID,
      exam_address,
      standby_exam_address,
      school,
      profession,
      level,
      take_info
    } = app.globalData.userInfo
    const data = deepClone({
      gender,
      nation,
      hk_address,
      name,
      phone,
      IDcard,
      education_bg,
      graduationSchool,
      graduationProfession,
      graduationTime,
      graduationID,
      exam_address,
      standby_exam_address,
      school,
      profession,
      level,
      take_info
    })
    // 处理性别
    if (data.gender === 0) {
      data.gender = '未知'
    }
    if (data.gender === 1) {
      data.gender = '男'
    }
    if (data.gender === 2) {
      data.gender = '女'
    }
    // 处理民族
    if (this.data.nationArr.indexOf(data.nation) !== -1)
      data.nation = this.data.nationArr.indexOf(data.nation)
    // 处理市区
    data.hk_address = data.exam_address ? data.hk_address.split(',') : []
    const hk_addressText = data.hk_address.slice(1, 3).join('')
    data.exam_address = data.exam_address ? data.exam_address.split(',') : []
    if(data.exam_address.length === 3 && data.exam_address[0] !== '广东省') data.exam_address = ['广东省','广州市','荔湾区']
    else data.exam_address = ['广东省'].concat(data.exam_address.slice(data.exam_address.length - 2, data.exam_address.length))
    const exam_addressText = data.exam_address.slice(1, 3).join('')
    console.log(exam_address,exam_addressText)
    data.standby_exam_address = data.standby_exam_address ? data.standby_exam_address.split(',') : []
    if(data.standby_exam_address.length === 3 && data.standby_exam_address[0] !== '广东省') data.standby_exam_address = ['广东省','广州市','荔湾区']
    else data.standby_exam_address = ['广东省'].concat(data.standby_exam_address.slice(data.standby_exam_address.length - 2, data.standby_exam_address.length))
    const standby_exam_addressText = data.standby_exam_address.slice(1, 3).join('')
    // 处理考前学历
    if (this.data.education_bgArr.indexOf(data.education_bg) !== -1)
      data.education_bg = this.data.education_bgArr.indexOf(data.education_bg)
    this.setData({
      formData: {
        gender,
        nation,
        hk_address,
        name,
        phone,
        IDcard,
        education_bg,
        graduationSchool,
        graduationProfession,
        graduationTime,
        graduationID,
        exam_address,
        standby_exam_address,
        school,
        profession,
        level,
        take_info
      },
      ...data,
      hk_addressText,
      exam_addressText,
      standby_exam_addressText
    })
  },
  // 点击标题显示输入框
  handelshowInput(e) {
    console.log(e)
    const title = e.currentTarget.dataset.title
    const hideStatus = Object.assign({
      ...this.data.hideStatus,
      [title]: false
    })
    this.setData({
      hideStatus
    })
    // console.log(this.data.hideStatus)
  },
  // 失去焦点隐藏输入框
  handelHideInput(e) {
    const title = e.currentTarget.dataset.title
    const hideStatus = Object.assign({
      ...this.data.hideStatus,
      [title]: true
    })
    this.setData({
      hideStatus
    })
  },
  // 每一项的值变化触发的事件
  formItemChange(e) {
    // const code = e.detail.code
    let value = e.detail.value
    const field = e.currentTarget.dataset.field
    console.log(field, 'field');
    console.log(value, 'value');
    let formData = {}
    
    // 是市区选择器，单独处理，只显示市、区
    if (field === 'hk_address' || field === 'exam_address' || field === 'standby_exam_address') {
      if(field === 'exam_address' || field === 'standby_exam_address') {
        // if(value ! === '') 
        console.log(value[0] === '广东省', '广东')
        if(value[0] !== '广东省') {
          wx.showToast({
            title: '只能选择广东省内哦~',
            icon:'none'
          })
          value = ['广东省','广州市','荔湾区']
        }
        
      }
        
        formData = Object.assign(this.data.formData, {
          [field]: value.slice(0, 3).join(',')
        })
      
      this.setData({
        [field + 'Text']: value.slice(1, 3).join('')
      })
      
      console.log(formData, 'formData');
    } else if (field === 'nation') {
      formData = Object.assign(this.data.formData, {
        [field]: this.data.nationArr[value]
      })
    } else if(field === 'education_bg'){
      formData = Object.assign(this.data.formData, {
        [field]: this.data.education_bgArr[value]
      })
    } else {
      formData = Object.assign(this.data.formData, {
        [field]: value
      })
    }

    console.log(field, value)
    console.log(e, 'www')

    this.setData({
      [field]: value,
      formData
    })
  },
  goNext() {
    this.selectComponent('#form').validate((valid, errors) => {
      console.log('valid', valid, errors)
      console.log('formData', this.data.formData)
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })
        }
      } else {

        request('/api/user/info', app.globalData.token, 'post', this.data.formData).then(res => {
          if (res.code === 200) {
            wx.showToast({
              title: '提交成功~',
              icon: 'none',
              duration: 2000,
              complete: () => {
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1
                  }, 3000)
                })
              }
            })
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        })

      }
    })


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})